package Util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//用于获取数据库连接和关闭的工具类
public class JDBCUtil {
    //配置文件信息，驱动程序加载
    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;
    static {
        InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties pros = new Properties();
        try {
            pros.load(is);
            driver = pros.getProperty("driverClassName");
            url = pros.getProperty("url");
            username = pros.getProperty("username");
            password = pros.getProperty("password");
            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //获取数据库连接
    public static Connection getConnection(){
        Connection conn =null;
        try {
            conn= DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接失败！请重新连接");
        }
        return conn;
    }
    //数据库相关资源的关闭方法
    public static void closeAll(Connection connection, PreparedStatement ps, ResultSet rs){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs=null;
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
//    //主函数调用
//    public static void main(String[] args) {
//        Connection con = JDBCUtil.getConnection();
//        System.out.println("获取数据库连接成功！");
//        closeAll(con, null, null);
//        System.out.println("成功关闭数据库连接！");
//    }
}
